/**
 *	Yggdrasil World Framework Toolkit
 *	(A component of the NeuroCoSA toolkit)
 *	Copyright (C) 2001-5 Stuart Meikle.
 *
 *	This is free software; you can redistribute it and/or
 *	modify it under the terms of the GNU Lesser General Public
 *	License as published by the Free Software Foundation; either
 *	version 2.1 of the License, or (at your option) any later version.
 *
 *	This library is distributed in the hope that it will be useful,
 *	but WITHOUT ANY WARRANTY; without even the implied warranty of
 *	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *	Lesser General Public License for more details.
 *
 * @author	Stuart Meikle
 * @version	2006-halloween
 * @license	LGPL
 */

package org.stumeikle.Yggdrasil;

import java.net.*;
import java.io.*;
import java.util.*;
import org.stumeikle.NeuroCoSA.DataBlock;

/**
 * actionwatcher class.
 * Server Side class, really a sub class of CreatureWrapper
 * which in turn is really a session.???
 *
 * this class waits on action objcets coming in from the client
 * and updates the server side copy appropriately. would not be
 * required if the available() method worked properly!!!
 * 
 * Copyright (C) Stuart Meikle Tue Mar 27 22:23:13 2001
 *
 */

public class ActionWatcher extends Thread
{
    private DataBlock		client_actions;
    private Socket		input_socket;
    private ObjectInputStream 	oipStream;

    ActionWatcher( Socket inputsoc )
    {
	client_actions = new DataBlock(); // just a default
	input_socket   = inputsoc;
    }

    public void	run()
    {
	//get the incoming actions
	//wait on senses from the server
	DataBlock	ab;

	try
	{
	    oipStream = new ObjectInputStream( input_socket.getInputStream() );
	}
	catch(Exception e)
	{
	    System.out.println("ACTIONWACHER:! problem creating input stream");
	}

	do
	{

	    ab = null;
	    try
	    {
        	ab = (DataBlock) oipStream.readObject();
		//don't care about the details for now!
		// *$ I ASSUME THAT THIS WILL READ IN THE OBJECT
	    }
	    catch(Exception e)
	    {
		ab= null;
	    }

	    if (ab!=null)
	    {
	        //copy over to the server. version in incoming object should be
	        //greater than previous action anyway.
		//System.out.println("ActionWatcher: received an action, v=" + ab.getVersion());

		// need an object copy thing here ...
		//no! now we need to clone the booger
		//System.out.println("DEBUG: incoming actions = " +
		//		   ab.getClass().getName() );

		client_actions = (DataBlock) ab.clone();

		//		client_actions.copy(ab); // K-rap.
	    }
	} while(true);

	//oipStream.close();
    }

    synchronized DataBlock	getActions()
    {
//System.out.println("DEBUG: getting actions, v=" + client_actions.getVersion() );
        return client_actions;
    }
}

